package com.xxc.smartcar.utils;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

public class PermissionUtils {
    // 网络相关权限
    public static final String[] NETWORK_PERMISSIONS = {
            android.Manifest.permission.INTERNET,
            android.Manifest.permission.ACCESS_NETWORK_STATE,
            android.Manifest.permission.ACCESS_WIFI_STATE,
            android.Manifest.permission.CHANGE_WIFI_STATE,
            android.Manifest.permission.CHANGE_NETWORK_STATE
    };

    // 权限请求码
    public static final int REQUEST_NETWORK_PERMISSIONS = 1001;

    /**
     * 检查并请求网络相关权限
     * @param activity 当前Activity
     * @return 是否已经拥有所有权限
     */
    public static boolean checkAndRequestNetworkPermissions(Activity activity) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            // Android 6.0以下无需动态申请权限
            return true;
        }

        // 需要申请的权限列表
        List<String> needPermissions = new ArrayList<>();

        for (String permission : NETWORK_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(activity, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                needPermissions.add(permission);
            }
        }

        // 如果有需要申请的权限
        if (!needPermissions.isEmpty()) {
            ActivityCompat.requestPermissions(
                    activity,
                    needPermissions.toArray(new String[0]),
                    REQUEST_NETWORK_PERMISSIONS
            );
            return false;
        }

        return true;
    }

    /**
     * 检查权限请求结果
     * @param grantResults 权限请求结果数组
     * @return 是否所有权限都被授予
     */
    public static boolean checkPermissionResults(int[] grantResults) {
        if (grantResults == null || grantResults.length == 0) {
            return false;
        }

        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 打开应用设置页面
     */
    public static void openAppSettings(Activity activity) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
        intent.setData(uri);
        activity.startActivityForResult(intent, REQUEST_NETWORK_PERMISSIONS);
    }
}

